#!/usr/bin/env python3

import argparse, sys
from bibliopixel.util.colors.closest_colors import closest_colors
from bibliopixel.util import colors, log

HELPS = {'help', '-h', '--h', '--help', '--h'}
USAGE = """Usage:
  bp-color color [color color ...]

Toggle between color names and color tuples

with --closest, prints the nearest named color.
"""


def main():
    run(make_args())


def make_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'colors', nargs='*',
        help='Color names or tuples',
        default='')

    parser.add_argument(
        '-l', '--list', action='store_true',
        help='List all the colors')

    parser.add_argument(
        '-c', '--closest', action='store_true',
        help='List the closest named colors')
    return parser.parse_args(sys.argv[1:])


def run(args):
    if args.list:
        log.printer(*sorted(colors.COLOR_DICT.items()), sep='\n')

    if not args.colors:
        if not args.list:
            raise ValueError('No colors supplied!')

    failures = []
    for c in args.colors:
        try:
            if args.closest:
                color = colors.names.to_color(c)
                closest = ('"%s"' % c for c in closest_colors(color))
                log.printer(c, end=': ')
                log.printer(*closest, sep=', ')
            else:
                log.printer(c, colors.toggle(c), sep=': ')
        except Exception as e:
            failures.append(c)
    if failures:
        s = '' if len(failures) == 1 else 's'
        failures = ', '.join('"%s"' % f for f in failures)
        raise ValueError('Did not understand color%s %s' % (s, failures))


if __name__ == '__main__':
    main()
